package com.h3c.nem.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eos.common.util.Result;
import com.eos.common.util.UserUtils;
import com.h3c.nem.client.EosSyncDataClient;
import com.h3c.nem.client.SapClient;
import com.h3c.nem.dto.LoginUserDTO;
import com.h3c.nem.dto.TbPreWorkerSeaDTO;
import com.h3c.nem.dto.client.NewWorkerClientDTO;
import com.h3c.nem.dto.client.PreWorkerClientDTO;
import com.h3c.nem.entity.*;
import com.h3c.nem.mapper.TbOfferWorkerMapper;
import com.h3c.nem.mapper.TbPreWorkerMapper;
import com.h3c.nem.service.*;
import com.h3c.nem.dto.TbPreWorkerDTO;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbPreWorkerServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-01-19
 * Description: tb_pre_worker serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class TbPreWorkerServiceImpl extends ServiceImpl<TbPreWorkerMapper, TbPreWorker> implements ITbPreWorkerService {

    @Resource
    private TbPreWorkerMapper tbPreWorkerMapper;

    @Autowired
    private ISdDeptService deptService;

    @Autowired
    private ISdAllWorkerService allWorkerService;

    @Autowired
    private TbOfferWorkerMapper offerWorkerMapper;

    @Autowired
    private CommService commService;
    @Autowired
    private ITbTeacherService teacherService;
    @Resource
    private ITbWorkerService workerService;
    @Resource
    private ISdEmailTemplateService emailTemplateService;
    @Autowired(required = false)
    private UserUtils userUtils;
    @Autowired
    private EosSyncDataClient eosSyncDataClient;
    @Autowired
    private SapClient sapClient;
    @Value("${hrss.nem.account}")
    private String hrssUId;
    @Value("${hrss.nem.password}")
    private String hrssPasswd;
    @Value("${eos.nem.account}")
    private String eosAccount;
    @Value("${eos.nem.password}")
    private String eosPasswd;

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<TbPreWorkerDTO> selectFuzzyByDto(TbPreWorkerSeaDTO dto) {
        //List<TbPreWorker> list = tbPreWorkerMapper.selectByExample(initFuzzyExample(dto));
        if (!StringUtils.isEmpty(dto.getDirectManagerId())) {
            dto.setDirectManagerIds(Arrays.asList(dto.getDirectManagerId().split(",")));
        }
        if (!StringUtils.isEmpty(dto.getHrbpId())) {
            dto.setHrbpIds(dto.getHrbpId().split(","));
        }
        if (!StringUtils.isEmpty(dto.getTeacherId())) {
            dto.setTeacherIds(dto.getTeacherId().split(","));
        }
        if (!StringUtils.isEmpty(dto.getDeptContactorId())) {
            dto.setDeptContactorIds(dto.getDeptContactorId().split(","));
        }

        List<TbPreWorkerDTO> list = tbPreWorkerMapper.queryList(dto);
        list.forEach(item -> {
            //拼接直属部门
            StringBuilder directDeptName = new StringBuilder(item.getDept1name());
            if (!StringUtils.isEmpty(item.getDept2name())) {
                directDeptName.append("\\").append(item.getDept2name());
            }
            if (!StringUtils.isEmpty(item.getDept3name())) {
                directDeptName.append("\\").append(item.getDept3name());
            }
            if (!StringUtils.isEmpty(item.getDept4name())) {
                directDeptName.append("\\").append(item.getDept4name());
            }
            item.setDirectDeptName(directDeptName.toString());
        });
        return list;
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(TbPreWorkerDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = IdWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return tbPreWorkerMapper.insertTbPreWorker(JSONObject.parseObject(JSON.toJSONString(dto), TbPreWorker.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(TbPreWorkerDTO dto) {
        String loginUserRole = commService.getLoginUserRole();
        if (!(commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN)
                || commService.checkLoginUserBP()
                || commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR))) {
            return 1;
        }
        SdDept directDept = deptService.getById(dto.getDirectDeptId());
        if (directDept == null) {
            throw new AppBusinessException("没有对应的部门");
        }
        String[] deptNames = directDept.getDeptNameChain().split("/");
        int deptLength = deptNames.length;
        dto.setDept1name(deptNames[1]);
        if (deptLength == 3) {
            dto.setDept2name(deptNames[2]);
            dto.setDept3name("");
            dto.setDept4name("");
        }
        if (deptLength == 4) {
            dto.setDept2name(deptNames[2]);
            dto.setDept3name(deptNames[3]);
            dto.setDept4name("");
        }
        if (deptLength == 5) {
            dto.setDept2name(deptNames[2]);
            dto.setDept3name(deptNames[3]);
            dto.setDept4name(deptNames[4]);
        }
        dto.setDirectDeptId(directDept.getDeptId());
        dto.setDirectDeptName(directDept.getDeptName());
        if (!StringUtils.isEmpty(dto.getTeacherInfo())) {
            TbTeacher teacher = teacherService.getById(dto.getTeacherInfo());
            if (teacher == null) {
                throw new AppBusinessException("思想导师没有对应的员工");
            }
            dto.setTeacherInfo(teacher.getTeacherName() + "/" + teacher.getTeacherId());
        }
        if (!StringUtils.isEmpty(dto.getDeptContactor())) {
            SdAllWorker deptContactor = allWorkerService.getById(dto.getDeptContactor());
            if (deptContactor == null) {
                throw new AppBusinessException("部门接口人没有对应的员工");
            }
            dto.setDeptContactor(deptContactor.getWorkerName() + "/" + deptContactor.getWorkerId());
        }
        if (!StringUtils.isEmpty(dto.getDirectManager())) {
            SdAllWorker directManager = allWorkerService.getById(dto.getDirectManager());
            if (directManager == null) {
                throw new AppBusinessException("直接上级没有对应的员工");
            }
            dto.setDirectManager(directManager.getWorkerName() + "/" + directManager.getWorkerId());
        }
        TbPreWorker dbWorker = getById(dto.getPreWorkerId());
        TbPreWorker worker = new TbPreWorker();
        BeanUtils.copyProperties(dto,worker);
        /*if (worker.getChangePlanJoinDate() != null) {
            if (!dbWorker.getChangePlanJoinDate().equals(worker.getChangePlanJoinDate())) {
                //计划入职日期变更
            }
            worker.setPlanJoinDate(worker.getChangePlanJoinDate());
            worker.setChangePlanJoinDate(null);
        }else{
            if (!dbWorker.getPlanJoinDate().equals(dto.getPlanJoinDate())) {
                //计划入职日期变更
            }
        }*/
        tbPreWorkerMapper.updateTbPreWorker(worker);
        return 1;
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(TbPreWorkerDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
            return tbPreWorkerMapper.deleteTbPreWorker(JSONObject.parseObject(JSON.toJSONString(dto), TbPreWorker.class));
            //return tbPreWorkerMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }

    @Override
    public File exportPreWorker(TbPreWorkerSeaDTO paramsDTO) {
        List<TbPreWorkerDTO> waitExpList = selectFuzzyByDto(paramsDTO);
        return commService.generateExportFile("待入职员工列表", BusiEnumDefine.PRE_WORKER_EXPORT, (List) waitExpList);
    }

    @Override
    public Map<String,Map<Object,Object>> calenderStatistics(String time, String deptId) {
        String loginUserRole = commService.getLoginUserRole();
        String loginUserId = commService.getLoginUserId();
        boolean adminAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN);
        boolean bpAuth = commService.checkLoginUserBP();
        boolean conAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR);
        boolean manAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_MANAGER);
        boolean gbbzAuth = commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_GBBZ);
        Map<String,Map<Object,Object>> resMap = new HashMap<>();
        Map<Object,Object> resMap1 = new HashMap<>();
        Map<Object,Object> resMap2 = new HashMap<>();
        resMap.put("waitJoin",resMap1);
        resMap.put("waitPass",resMap2);
        Set<Integer> authDeptIds = null;
        if (adminAuth) {}else if (bpAuth || conAuth || manAuth || gbbzAuth){
            authDeptIds = deptService.getAuthDeptIds(bpAuth, conAuth, manAuth, gbbzAuth);
            if (authDeptIds.isEmpty()) {
                return resMap;
            }
        } else {
            return resMap;
        }
        String[] ym = time.split("-");

        int year = 0;
        int month = 0;
        try {
            year = Integer.parseInt(ym[0]);
            month = Integer.parseInt(ym[1]);
        } catch (NumberFormatException e) {
            throw new AppBusinessException("日期格式不正确");
        }

        if (month > 12 || month < 1) {
            throw new AppBusinessException("日期格式不正确");
        }
        boolean isMore18;
        if (adminAuth || gbbzAuth){
            isMore18 = true;
        }else{
            isMore18 = false;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
//        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Date startTime = calendar.getTime();
        calendar.add(Calendar.WEEK_OF_YEAR,2);
        calendar.add(Calendar.DAY_OF_MONTH,-1);
        Date endTime = calendar.getTime();
        List<Map<String, Object>> waitJoinList = offerWorkerMapper.countPreGroupByDay(startTime, endTime, authDeptIds);
        List<Map<String,Object>> _2WePassedWorkerList = workerService.get2WePassedWorkerList(startTime,endTime,authDeptIds,isMore18,conAuth? loginUserId:null);
        /*(new QueryWrapper<TbWorker>()
                .select("COUNT(1) count","date_format(pass_date,'%Y-%m-%d') day")
                .ge("pass_date", startTime)
                .le("pass_date", endTime)
                .in(deptIdList != null, "direct_dept_id", deptIdList)
                .groupBy("day"));*/
        if (waitJoinList != null) {
            for (Map<String, Object> item : waitJoinList) {
                resMap1.put(item.get("day"),item.get("count"));
            }
        }
        if (_2WePassedWorkerList != null) {
            for (Map<String, Object> item : _2WePassedWorkerList) {
                resMap2.put(item.get("day"),item.get("count"));
            }
        }
        resMap.put("waitJoin",resMap1);
        resMap.put("waitPass",resMap2);
        return resMap;
    }

    @Override
    @Transactional
    public void importPreWorker(MultipartFile file) {
        String loginUserRole = commService.getLoginUserRole();
        if (!(commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_ADMIN)
                || commService.checkLoginUserBP()
                || commService.checkLoginUserRole(BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR))) {
            return ;
        }
        String excelJsonString = commService.parseExcelByTemplate(BusiEnumDefine.PRE_WORKER_EXPORT, file);
        List<TbPreWorker> tbPreWorkers = JSONArray.parseArray(excelJsonString, TbPreWorker.class);
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;

        tbPreWorkers.forEach(item -> {
            if (!StringUtils.isEmpty(item.getDeptContactor())) {
                String deptContactorId = item.getDeptContactor().split("/")[1];
                if (dataCacheMap.containsKey("allworker-" + deptContactorId)) {
                    SdAllWorker deptContactor = (SdAllWorker) dataCacheMap.get("allworker-" + deptContactorId);
                    item.setDeptContactor(deptContactor.getWorkerName()+ "/" + deptContactorId );
                }else{
                    throw new AppBusinessException("没有工号为" + deptContactorId + "的员工");
                }
            }
            if (!StringUtils.isEmpty(item.getTeacherInfo())) {
                String teacherId = item.getTeacherInfo().split("/")[1];
                if (dataCacheMap.containsKey("allworker-" + teacherId)) {
                    SdAllWorker teacher = (SdAllWorker) dataCacheMap.get("allworker-" + teacherId);
                    item.setDeptContactor(teacher.getWorkerName() + "/" + teacherId );
                }else{
                    throw new AppBusinessException("没有工号为" + teacherId + "的思想导师");
                }
            }
            if (!StringUtils.isEmpty(item.getDirectManager())) {
                String teacherId = item.getDirectManager().split("/")[1];
                if (dataCacheMap.containsKey("allworker-" + teacherId)) {
                    SdAllWorker teacher = (SdAllWorker) dataCacheMap.get("allworker-" + teacherId);
                    item.setDeptContactor( teacher.getWorkerName() + "/" + teacherId);
                }else{
                    throw new AppBusinessException("没有工号为" + teacherId + "的员工");
                }
            }
            if (!StringUtils.isEmpty(item.getDirectDeptId())) {
                if (dataCacheMap.containsKey("dept-" + item.getDirectDeptId())) {
                    SdDept sdDept = (SdDept) dataCacheMap.get("dept-" + item.getDirectDeptId());
                    String[] deptNames = sdDept.getDeptNameChain().split("/");
                    int deptLength = deptNames.length;
                    item.setDept1name(deptNames[1]);
                    if (deptLength == 3) {
                        item.setDept2name(deptNames[2]);
                        item.setDept3name("");
                        item.setDept4name("");
                    }
                    if (deptLength == 4) {
                        item.setDept2name(deptNames[2]);
                        item.setDept3name(deptNames[3]);
                        item.setDept4name("");
                    }
                    if (deptLength == 5) {
                        item.setDept2name(deptNames[2]);
                        item.setDept3name(deptNames[3]);
                        item.setDept4name(deptNames[4]);
                    }
                    item.setDirectDeptId(sdDept.getDeptId());
                }else{
                    throw new AppBusinessException("没有部门编号为" + item.getDirectDeptId() + "的部门");
                }
            }
            tbPreWorkerMapper.updateTbPreWorker(item);
        });
    }

    @Override
    public void sendMessageToTeacher(List<String> workerIds) {
        List<TbPreWorker> preWorkers = list(new QueryWrapper<TbPreWorker>().in("pre_worker_id", workerIds));
        Set<String> teacherInfos = preWorkers.stream().map(TbPreWorker::getTeacherInfo).collect(Collectors.toSet());
        SdEmailTemplate emailTemplate = emailTemplateService.getById("PREWORKER_TEACHER_EMAIL");
        String emailContent = emailTemplate.getEmailTemplateContent();
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        for (String teacherInfo : teacherInfos) {
            String[] idAndName = teacherInfo.split("/");
            String teacherId = idAndName[0];
            String teacherName = idAndName[1];
            Object teacherCache = dataCacheMap.get("allworker-" + teacherId);
            SdAllWorker teacher ;
            if (teacherCache == null) {
                teacher = allWorkerService.getById(teacherId);
            }else{
                teacher = (SdAllWorker) teacherCache;
            }
            String preWorkerNames = preWorkers.stream()
                    .filter(i -> i.getTeacherInfo().equals(teacherInfo))
                    .map(i -> i.getPreWorkerId() + "/" + i.getWorkerName())
                    .collect(Collectors.joining(","));
            String emailContentFin = emailContent.replace("{收件人}", teacherName).replace("{被选员工}", preWorkerNames).replace("{角色}", "思想导师");
            SdNoticeRecord email = new SdNoticeRecord();
            email.setNoticeId(IdWorker.nextId() + "");
            email.setApplyUserId(commService.getLoginUserId());
            email.setTargetEmail(teacher.getEmail());
            email.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            email.setNoticeContent(emailContentFin);
            email.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
            commService.sendMessage(email);
        }

    }

    public void sendMessageToManager(List<String> workerIds){
        /*List<TbPreWorker> preWorkers = list(new QueryWrapper<TbPreWorker>().in("pre_worker_id", workerIds));
        Set<String> teacherInfos = preWorkers.stream().map(TbPreWorker::getTeacherInfo).collect(Collectors.toSet());
        SdEmailTemplate emailTemplate = emailTemplateService.getById("PREWORKER_TEACHER_EMAIL");
        String emailContent = emailTemplate.getEmailTemplateContent();
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        for (String teacherInfo : teacherInfos) {
            String[] idAndName = teacherInfo.split("/");
            String teacherId = idAndName[0];
            String teacherName = idAndName[1];
            Object teacherCache = dataCacheMap.get("allworker-" + teacherId);
            SdAllWorker teacher ;
            if (teacherCache == null) {
                teacher = allWorkerService.getById(teacherId);
            }else{
                teacher = (SdAllWorker) teacherCache;
            }
            String preWorkerNames = preWorkers.stream()
                    .filter(i -> i.getTeacherInfo().equals(teacherInfo))
                    .map(i -> i.getPreWorkerId() + "/" + i.getWorkerName())
                    .collect(Collectors.joining(","));
            String emailContentFin = emailContent.replace("{收件人}", teacherName).replace("{被选员工}", preWorkerNames).replace("{角色}", "思想导师");
            SdNoticeRecord email = new SdNoticeRecord();
            email.setNoticeId(IdWorker.nextId() + "");
            email.setApplyUserId(commService.getLoginUserId());
            email.setTargetEmail(teacher.getEmail());
            email.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
            email.setNoticeContent(emailContentFin);
            email.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
            commService.sendMessage(email);
        }*/
    }

    @Override
    public void updatePlanTime(TbPreWorkerDTO paramsDTO) {
        String preWorkerId = paramsDTO.getPreWorkerId();
        TbPreWorker dbWorker = getById(preWorkerId);
        if (dbWorker == null) {
            throw new AppBusinessException("不存在该预备员工");
        }
        if (paramsDTO.getChangePlanJoinDate() == null) {
            throw new AppBusinessException("变更时间不能为空");
        }
        String email ;
        if (paramsDTO.getSendBpEmail() == null) {
            SdDept sdDept = (SdDept) CommService.dataCacheMap.get("dept-" + dbWorker.getDirectDeptId());
            SdAllWorker sendBp = (SdAllWorker) CommService.dataCacheMap.get("allworker-" + sdDept.getDeptManagerId());
            email = sendBp.getEmail();

        }else{
            email = paramsDTO.getSendBpEmail();
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SdEmailTemplate pretobp = emailTemplateService.getById("PRETOBP");
        SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
        sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
        sdNoticeRecord.setFlowId("-1");
  /*
        sdNoticeRecord.setApplyUserId(loginUserId);*/
        sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
/*        sdNoticeRecord.setTargetId(allWorker.getWorkerId());
        sdNoticeRecord.setTargetName(allWorker.getWorkerName());*/
        sdNoticeRecord.setTargetEmail(email);
        sdNoticeRecord.setCopyToEmail("");
        sdNoticeRecord.setNoticeTitle(pretobp.getEmailTemplateTitle());
        sdNoticeRecord.setNoticeContent(pretobp.getEmailTemplateContent()
                .replace("{预备员工姓名/预备员工号}",dbWorker.getWorkerName() + "/" + dbWorker.getPreWorkerId())
                .replace("{origReportDate}",sf.format(dbWorker.getPlanJoinDate()))
                .replace("{newReportDate}",sf.format(paramsDTO.getPlanJoinDate())));
        sdNoticeRecord.setCreateTime(new Date());
        commService.sendMessage(sdNoticeRecord);
        update(new UpdateWrapper<TbPreWorker>()
                .eq("pre_worker_id",preWorkerId)
                .set("send_bp_id",paramsDTO.getSendBpEmail())
                .set("change_plan_join_date",paramsDTO.getChangePlanJoinDate()));

    }

    @Override
    @Transactional
    public void syncPreWorker() {
        LinkedList<TbPreWorker> preWorkerList = new LinkedList<>();
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        Date now = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat planSf = new SimpleDateFormat("yyyyMMdd");
        String token = "Bearer " + userUtils.getToken(eosAccount,eosPasswd);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("reportDate",sf.format(now));
        String workerData = eosSyncDataClient.syncPreWorker(token,jsonObject.toJSONString());
        log.info("eos返回：" + workerData);
        Result<List<PreWorkerClientDTO>> eosResult = JSON.parseObject(workerData, new TypeReference<Result<List<PreWorkerClientDTO>>>() {});

        if (eosResult.getFlag()) {
            Calendar instance = Calendar.getInstance();
            List<PreWorkerClientDTO> data = eosResult.getData();
            try {
                for (PreWorkerClientDTO item : data) {
                    TbPreWorker preWorker = new TbPreWorker();
                    BeanUtils.copyProperties(item,preWorker);
                    if (item.getEmail() == null) {
                        preWorker.setEmail("-1");
                    }
                    //不存放身份证信息
                    preWorker.setIdCardNo("");
                    preWorker.setProbationMonth(3);
                    preWorker.setWorkerStatus(1);
                    preWorker.setCreateTime(now);
                    preWorker.setRegistDate(now);
                    preWorker.setPlanJoinDate(now);
                    preWorker.setDept1name("");
                    preWorker.setSex(item.getSex().equals("男") ? 1 : 2);
                    preWorker.setPlanJoinDate(planSf.parse(item.getPlanJoinDate()));
                    instance.setTime(preWorker.getPlanJoinDate());
                    instance.add(Calendar.MONTH,3);
                    preWorker.setPassDate(instance.getTime());
                    SdDept directDept = (SdDept) dataCacheMap.get("dept-" + item.getDirectDeptId());
                    String [] deptNameChain;
                    if (directDept == null) {
                        SdDept dbDept = deptService.getById(item.getDirectDeptId());
                        if (dbDept == null) {
                            deptNameChain = new String[]{};
                        }else{
                            deptNameChain = dbDept.getDeptNameChain().split("/");
                        }
                    }else{
                        deptNameChain = directDept.getDeptNameChain().split("/");
                    }

                    int deptLength = deptNameChain.length;
                    if (deptLength == 2) {
                        preWorker.setDept1name(deptNameChain[1]);
                    } else if (deptLength == 3) {
                        preWorker.setDept1name(deptNameChain[1]);
                        preWorker.setDept2name(deptNameChain[2]);
                    } else if (deptLength == 4) {
                        preWorker.setDept1name(deptNameChain[1]);
                        preWorker.setDept2name(deptNameChain[2]);
                        preWorker.setDept3name(deptNameChain[3]);
                    }else if (deptLength == 5) {
                        preWorker.setDept1name(deptNameChain[1]);
                        preWorker.setDept2name(deptNameChain[2]);
                        preWorker.setDept3name(deptNameChain[3]);
                        preWorker.setDept3name(deptNameChain[4]);
                    }
                    preWorkerList.add(preWorker);
                }

            }catch (ParseException e){
                log.error("同步失败");
            }
            saveOrUpdateBatch(preWorkerList);
        }else{
            log.error("获取中台待入职员工数据失败：" + eosResult.getMessage());
            throw new AppBusinessException("获取中台待入职员工数据失败");
        }
    }

    @Override
    public void confirmChangePlanDate(TbPreWorkerDTO param) {
        TbPreWorker dbPreWorker = getById(param.getPreWorkerId());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        String sapToken = commService.getSapToken(hrssUId,hrssPasswd);
        JSONObject jsonObject = new JSONObject();
        String time = sf.format(param.getChangePlanJoinDate());
        if (!param.getChangePlanJoinDate().equals(dbPreWorker.getChangePlanJoinDate())){
            jsonObject.put("ConfirmEntryDate",time);
        }else{
            jsonObject.put("ConfirmEntryDate","");
        }
        jsonObject.put("HC_NO",dbPreWorker.getPreWorkerId());
        jsonObject.put("ConfirmHRBP",commService.getLoginUserId());
        JSONObject res = sapClient.ConfirmEntryDate(jsonObject.toJSONString(), sapToken);
        if ((boolean)res.get("success")) {
            update(new UpdateWrapper<TbPreWorker>()
                    .set("change_plan_join_date",null)
                    .set("plan_join_date",param.getChangePlanJoinDate())
                    .eq("pre_worker_id",dbPreWorker.getPreWorkerId()));
            //发送邮件
            SdDept dept = deptService.getById(dbPreWorker.getDirectDeptId());
            String [] sendEmailWorkerIds = new String[]{dept.getBpUserId(),dbPreWorker.getDirectManager().split("/")[1],dept.getContactorId()};
            List<SdAllWorker> sendWorkers = allWorkerService.list(new QueryWrapper<SdAllWorker>().in("worker_id", sendEmailWorkerIds));
            String emails = sendWorkers.stream().map(SdAllWorker::getEmail).collect(Collectors.joining(","));
            if (!emails.contains(dbPreWorker.getSendBpEmail())) {
                emails = emails + "," + dbPreWorker.getSendBpEmail();
            }

            SdEmailTemplate emailTemplate = emailTemplateService.getById("CONFIRM_PLAN_DATE");
            String replace = emailTemplate.getEmailTemplateContent()
                    .replace("{预备员工姓名/预备员工号}", dbPreWorker.getWorkerName() + "/" + dbPreWorker.getPreWorkerId())
                    .replace("{newReportDate}", time);
            SdNoticeRecord sdNoticeRecord = new SdNoticeRecord();
            sdNoticeRecord.setNoticeId(IdWorker.nextId() + "");
  /*      sdNoticeRecord.setFlowId(item.getFlowId());
        sdNoticeRecord.setApplyUserId(loginUserId);*/
            sdNoticeRecord.setNoticeType(BusiEnumDefine.NOTICE_TYPE_EMAIL);
/*        sdNoticeRecord.setTargetId(allWorker.getWorkerId());
        sdNoticeRecord.setTargetName(allWorker.getWorkerName());*/
            sdNoticeRecord.setTargetEmail(emails);
            sdNoticeRecord.setCopyToEmail("");
            sdNoticeRecord.setNoticeTitle(emailTemplate.getEmailTemplateTitle());
            sdNoticeRecord.setNoticeContent(replace);
            sdNoticeRecord.setCreateTime(new Date());
            commService.sendMessage(sdNoticeRecord);
        }else{
            log.error("确认计划入职时间---->同步到hrss失败" + res.get("message"));
            throw new AppBusinessException("确认失败");
        }
    }
}
